package com.multicampus.sample.lucene.search.remote;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;

import org.apache.lucene.analysis.cjk.CJKAnalyzer;
import org.apache.lucene.document.DateTools;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.RemoteSearchable;
import org.apache.lucene.search.Searchable;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;

public class SearchServer {
	public static void indexDirectory(Directory directory, String path) throws Exception{
		IndexWriter writer = new IndexWriter(directory, new CJKAnalyzer(), true);

		indexDocs(writer, new File(path));
		writer.optimize();
		writer.close();
	}

	public static void indexDocs(IndexWriter writer, File file)
			throws IOException {
		// do not try to index files that cannot be read
		if (file.canRead()) {
			if (file.isDirectory()) {
				String[] files = file.list();
				// an IO error could occur
				if (files != null) {
					for (int i = 0; i < files.length; i++) {
						indexDocs(writer, new File(file, files[i]));
					}
				}
			} else {
				try {
					Document doc = new Document();
					doc.add(new Field("path", file.getPath(), Field.Store.YES,
							Field.Index.UN_TOKENIZED));
					doc.add(new Field("modified", DateTools.timeToString(file
							.lastModified(), DateTools.Resolution.MINUTE),
							Field.Store.YES, Field.Index.UN_TOKENIZED));
					doc.add(new Field("title", file.getName(), Field.Store.YES,
							Field.Index.UN_TOKENIZED));
					doc.add(new Field("contents", new FileReader(file)));

					writer.addDocument(doc);
				} catch (FileNotFoundException fnfe) {
					;
				}
			}
		}
	}
	
	public static void main(String[] args) throws Exception{
		RAMDirectory[] directories = new RAMDirectory[]{new RAMDirectory(), new RAMDirectory()};
		
		indexDirectory(directories[0], "src/main/resources/documents/multisearcher1");
		indexDirectory(directories[1], "src/main/resources/documents/multisearcher2");
		
		Searchable[] searchables = new Searchable[2];
		
		for(int i = 0 ; i < searchables.length ; i++){
			searchables[i] = new IndexSearcher(directories[i]);
		}
		
		LocateRegistry.createRegistry(1099);
		
		RemoteSearchable search1 = new RemoteSearchable(searchables[0]);
		Naming.rebind("//localhost/Searcher1", search1);
		
		RemoteSearchable search2 = new RemoteSearchable(searchables[0]);
		Naming.rebind("//localhost/Searcher2", search2);
		
		System.out.println("Server started");
	}

}
